<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];

    require_once($rootDir.'/classes/LeproBJAppSettings.class.php');
    require_once($rootDir.'/classes/SessionManager.class.php');
    
    /* function precheck_page($url, $cookie='') {
        /* $url = parse_url($url);
        
        if (!isset($url['port'])) {
          if ($url['scheme'] == 'http') { $url['port']=80; }
          elseif ($url['scheme'] == 'https') { $url['port']=443; }
        }
        
        $url['query']=isset($url['query'])?$url['query']:'';
    
        $url['protocol']=$url['scheme'].'://';
        $eol="\r\n";
    
        $headers =  "GET ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
                    "Host: ".$url['host'].$eol.
                    "Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
                    "Content-Type: text/html;".$eol.
                    "Content-Length: ".strlen($url['query']).$eol.
                    "Cookie: ".$cookies.$eol.
                    "Connection: close".$eol.
                    $eol.$url['query'];        
        
        $fp = fsockopen($url['host'], $url['port']);
        $result = '';
        if ($fp) {
          fputs($fp, $headers);
          while(!feof($fp))
          {
            $result .= fgets($fp);
          }
          fclose($fp);
        } 
        return $result;
        return get_headers($url);
    } */

    function file_post_contents($url, $cookie='',$headers=false) { // based on: http://php.net/manual/function.file-get-contents.php#80435
        $url = parse_url($url);
    
        if (!isset($url['port'])) {
          if ($url['scheme'] == 'http') { $url['port']=80; }
          elseif ($url['scheme'] == 'https') { $url['port']=443; }
        }
        $url['query']=isset($url['query'])?$url['query']:'';
    
        $url['protocol']=$url['scheme'].'://';
        $eol="\r\n";
    
        $headers =  "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
                    "Host: ".$url['host'].$eol.
                    "Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
                    "Content-Type: application/x-www-form-urlencoded".$eol.
                    "Content-Length: ".strlen($url['query']).$eol.
                    "Cookie: ".$cookie.$eol.
                    $eol.$url['query'];
        $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
        if($fp) {
          fputs($fp, $headers);
          $result = '';
          while(!feof($fp)) { $result .= fgets($fp, 128); }
          fclose($fp);
          if (!$headers) {
            //removes headers
            $pattern="/^.*\r\n\r\n/s";
            $result=preg_replace($pattern,'',$result);
          }
          return $result;
        }
    }    
    
    function implode_cookies($cookies) {
        $output = '';
        foreach($cookies as $name => $value) {
            $output .= $name.'='.$value.'; ';
        }
        return $output;    
    }

    class LeproHelper {
    
        public static $DIRTY_OFFSET = 5000000;
        /*
        private static $USER = 'zokotuhaFly';
        private static $USER_ID = 15140;
        private static $USER_PASS = '*******************';
        */
        private static $COOKIES = array (
                'lepro.sid' => '71643c86081f5745fce3009d1a14b490',
                'lepro.uid' => '15140',
                'domain'    => '.leprosorium.ru',
                'lepro.gstqcsaahbv20' => '',
                'lepro.iamarobot' => '0');
        private static $LSESSION_ID = '71643c86081f5745fce3009d1a14b490';
                
        private static $LOGIN_FORM_RE = '/<form\s[^>]*action=\"\/login\/\"/';
        private static $LOGINCODE_RE = '/<img\s[^>]*alt=\"captcha\"[^>]*src=\"\/captchaa\/(\w{16})\"/';
           
        private static $KARMA_RE = '<span\s[^>]*class="rating"[^>]*><em>(-?\d*)';
        private static $NICKNAME_RE = '<\/div>\s*<h2>\s*<a\s[^>]*href="">([^<]*)';
        private static $VOICE_AND_RATING_RE = '<table\s*[^>]*id="userstat">\s*<tr>\s*<td.*<\/td>\s*<td>\s*[^<]*<strong>(-?\d*)[\s\w<\/>.]*<tr>\s*<td.*<\/td>\s*<td>\s*[^<]*(?:<strong>(-?\d*)|(-?\d*)[^>]*\d)';
        private static $DIRTY_RATING_AND_VOICE_RE = '<table\s*[^>]*id="userstat">\s*<tr>\s*<td.*<\/td>\s*<td>\s*[^<]*<a.*\/a>[^\d]*(-?\d*)[^\d]*(-?\d*)';
        
        private static $SID_COOCKIE_RE = '/lepro.sid=([\w]*);/';               
        
        private function __construct() {
        }
        
        private function __clone() {
        }
        
        // TODO: change file_get_contents with curl or fsockopen / get_headers, but they mess up with leprosorium 302 / 404
        
        public static function login($loginCode, $captcha) {
            /* $postRes = file_post_contents('http://leprosorium.ru/login/?user='.self::$USER.'&pass='.self::$USER_PASS.'&captcha='.$captcha.'&logincode='.$loginCode, implode_cookies(self::$COOKIES));
            if (preg_match(self::$SID_COOCKIE_RE, $postRes, $matches) > 0) {
                self::$LSESSION_ID = $matches[1];
                self::$COOKIES['lepro.sid'] = self::$LSESSION_ID;
                self::$COOKIES['lepro.uid'] = self::$USER_ID;
                return $matches[1];                
            } else return null; */
            $loginSettings = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/.login.ini');            
            $postRes = file_post_contents('http://leprosorium.ru/login/?user='.$loginSettings["user"].'&pass='.$loginSettings["pass"].'&captcha='.$captcha.'&logincode='.$loginCode, implode_cookies(self::$COOKIES));
            if (preg_match(self::$SID_COOCKIE_RE, $postRes, $matches) > 0) {
            	SessionManager::registerVar('clsessionid', $matches[1]);
            	SessionManager::registerVar('cluid', $loginSettings["userid"]);
                self::$LSESSION_ID = $matches[1];
                self::$COOKIES['lepro.sid'] = self::$LSESSION_ID;
                self::$COOKIES['lepro.uid'] = $loginSettings["userid"];
                return $matches[1];                
            } else return null;
        }
        
        public static function getLoginCode($hardTry=false) {
            $dirtyPage = $hardTry ? self::getDirtyPage(null, true, false) : self::getDirtyPage();
            
            if (!self::isLoggedIn($dirtyPage)) {
                if (preg_match(self::$LOGINCODE_RE, $dirtyPage, $matches) > 0) {
                    return $matches[1];
                } else return -1;            
            } else return null; // already logged in
        }
        
        public static function isLoggedIn($dirtyPage=null) {
            $dirtyPage = ($dirtyPage != null) ? $dirtyPage : self::getDirtyPage();
            
            return !(preg_match(self::$LOGIN_FORM_RE, $dirtyPage) > 0);
        }        
        
        private static function getDirtyPage($pageURL='http://leprosorium.ru/users/1', $isLeproPage=true, $doSendCookies=true, $doBinaryLoad=false, $emulateRobot=false, $useSession=true) {
            //echo $pageURL.'; '.$isLeproPage.'; ';
            if (!$isLeproPage) $doSendCookies = false;
            if ($pageURL == null || $pageURL == '') $pageURL = 'http://leprosorium.ru/users/1';
            
            // var_dump(precheck_page($pageURL, $doSendCookies ? implode_cookies(self::$COOKIES) : ''));
            $cookiesPack = self::$COOKIES;
            if ($emulateRobot) $cookiesPack['lepro.iamarobot'] = '1';
            if ($useSession) {
                if (SessionManager::isVarSet('clsessionid')) $cookiesPack['lepro.sid'] = SessionManager::getVar('clsessionid');
                if (SessionManager::isVarSet('cluid')) $cookiesPack['lepro.uid'] = SessionManager::getVar('cluid');
            } 
            
            $eol="\r\n";            
            $context_options = array (
                'http' => array (
                    'method' => 'GET',
                    'header'=> "Content-type: "."text/html; charset=windows-1251;".$eol.
                               "Host: ".($isLeproPage ? "leprosorium.ru" : "dirty.ru").$eol.
                               "Referer: ".($isLeproPage ? "http://leprosorium.ru/login/" : "http://dirty.ru").$eol.
                               ($doSendCookies ? "Cookie: ".implode_cookies($cookiesPack).$eol : '')
                )
            );

            $context = stream_context_create($context_options);
            $oldErrRep = error_reporting(E_ERROR); // not to echo 404 warning (tried fsock|HEAD request and get_headers, but they mess up with Lepro's 302->302->302->200...)
            $dirtyPage = file_get_contents($pageURL, $doBinaryLoad ? FILE_BINARY : FILE_TEXT, $context);
            error_reporting($oldErrRep);
            if (($dirtyPage == null) || ($dirtyPage == false)) return -1;
            if (!$doBinaryLoad) $dirtyPage = mb_convert_encoding($dirtyPage, 'UTF-8', 'windows-1251');
            return $dirtyPage;
        }
        
        private static function getUserPage($userId, $isDirtyUser=null) {
            $isDirtyUser = ($isDirtyUser != null) ? $isDirtyUser : self::isDirtyUser($userId);
            $userId = $isDirtyUser ? ($userId - self::$DIRTY_OFFSET) : $userId;
            // echo $userId.'; ';
            $hostname = $isDirtyUser ? 'dirty.ru' : 'leprosorium.ru';
            return self::getDirtyPage('http://'.$hostname.'/users/'.$userId, !$isDirtyUser); // do not send cookies if dirty user
        }
        
        public static function getCaptcha($loginCode) {
            // return file_get_contents('http://leprosorium.ru/captchaa/'.$loginCode);
            return self::getDirtyPage('http://leprosorium.ru/captchaa/'.$loginCode, true, true, true, true, false);
        }
        
        public static function logout() {
            self::getDirtyPage('http://leprosorium.ru/logout');
        }
        
        public static function isDirtyUser($userId) {
            return ($userId >= self::$DIRTY_OFFSET);
        }
        
        public static function getExternalUserId($userId, $prefix='?') {
            return ($userId >= self::$DIRTY_OFFSET) ? $prefix.($userId - self::$DIRTY_OFFSET) : $userId;
        }
        
        public static function getUserData($userId) {
            $isDirtyUser = self::isDirtyUser($userId);
            $userPage = self::getUserPage($userId, $isDirtyUser);
            if (($userPage != -1) && self::isLoggedIn($userPage)) {
                if ($isDirtyUser) {
                    if (preg_match('/'.self::$KARMA_RE.'[^*]*'.self::$NICKNAME_RE.'[^*]*'.self::$DIRTY_RATING_AND_VOICE_RE.'/', $userPage, $matches) > 0) {
                        return array (
                            'userId' => $userId,
                            'userName' => $matches[2],
                            'fd' => true,
                            'karma' => $matches[1],
                            'voice' => $matches[4],
                            'rating' => $matches[3]
                            );
                    } else return -1;
                } else {
                    if (preg_match('/'.self::$KARMA_RE.'[^*]*'.self::$NICKNAME_RE.'[^*]*'.self::$VOICE_AND_RATING_RE.'/', $userPage, $matches) > 0) {
                        return array (
                            'userId' => $userId,
                            'userName' => $matches[2],
                            'fd' => false,
                            'karma' => $matches[1],
                            'voice' => $matches[3],
                            'rating' => $matches[4]
                            );
                    } else return -1;
                }
            } else return null;
        }
        
        public static function checkUserProfileForCard($userId, $cardSummary) {
            $lcard_re = '/<a[^>]*href="'.LeproBJAppSettings::$APP_HOST_RE.'">\s*'.'<img[^>]*src="'.
                        LeproBJAppSettings::$APP_HOST_RE.LeproBJAppSettings::$IMGS_PATH_RE.
                        $cardSummary['file'].'\.'.LeproBJAppSettings::$CARDS_FNAME_EXT.
                        '[^>]*alt="'.LeproBJAppSettings::$APP_TITLE.'"[^>]*title="'.
                        $cardSummary['name'].'"[^>]*><\/\s*a>/';
            $scard_re = '/\[<a[^>]*href="'.LeproBJAppSettings::$APP_HOST_RE.'">\s*'.
                        $cardSummary['html'].'\s*<\/\s*a>\]\s*'.'<a[^>]*href="'.
                        LeproBJAppSettings::$APP_HOST_RE."[^>]*>".$cardSummary['name'].
                        '<\/\s*a>/';            
               
            $isDirtyUser = self::isDirtyUser($userId);
            $userPage = self::getUserPage($userId, $isDirtyUser); 
            if (($userPage != -1) && self::isLoggedIn($userPage)) {
                return ((preg_match($lcard_re, $userPage) > 0) || (preg_match($scard_re, $userPage) > 0)); 
            } else return -1;     
        } 
    
    } 

?>
